# -*- coding: utf-8 -*-
# @Time    : 2019/12/18 10:14
# @Author  : Damn7Kx
# @Software: PyCharm
import datetime
import json
import random
from urllib.parse import unquote
import scrapy
from NewsSpider.items import NewsItem
from NewsSpider.tools.utils import Utils
from NewsSpider.tools.filter_time import Times
from NewsSpider.tools.parse_html import extract_html
from NewsSpider.tools.redis_db import Redis_DB
from w3lib.html import remove_tags


class JieMianNews(scrapy.Spider):
    '''
        api获取 详情页访问 时间戳翻页
    '''

    name = 'Jiemian'
    types = ['152','117','643','644','123','138','121','137','139','124','125','127',
             '322','183','259','495','505','181','118','260','669','202','203','122','505',
             '158','64','142','519','937','921','673','140','463','530','830','666','294',
             '182','1130','406','313','447','1065']

    Ua = [
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/72.0.3626.101 Mobile/15E148 Safari/605.1",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/15.0b13894 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/8.1.1 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/16.0.14.122053 Mobile/16D57 Safari/9537.53",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/2 Mobile/16D57",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/12.0.5.3 Version/7.0 Mobile/16D57 Safari/9537.53",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 EdgiOS/42.10.3 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 unknown BingWeb/6.9.8.1",
    ]
    headers = {
        "User-Agent": random.choice(Ua),
    }
    t = Times()
    count = 0
    redis = Redis_DB()

    custom_settings = {
        'DOWNLOADER_MIDDLEWARES': {
            'NewsSpider.middlewares.ProxyIPMiddleware': 544,
            'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
        },
        'ITEM_PIPELINES': {
            'NewsSpider.pipelines.KafkaPipeline': 544,
        }
    }
    def start_requests(self):
        for type in self.types:
            base_url = f'https://papi.jiemian.com/app/channel/index?version=6.6.2.0&id={type}&page=1'
            yield scrapy.Request(base_url, headers=self.headers,callback=self.parse_text,dont_filter=True,meta={"type":type,"page":1})

    def parse_text(self,response):
        print("正在访问起始页:",response.url)
        datas = json.loads(response.text)
        if datas:
            data_ = datas['result']['list']
            type = response.meta['type']
            page = response.meta['page']
            if page > 3:
                pass
            else:
                new_page = page + 1
                # 下一页的翻页
                base_url = f'https://papi.jiemian.com/app/channel/index?version=6.6.2.0&id={type}&page={str(new_page)}'
                yield scrapy.Request(base_url, headers=self.headers, callback=self.parse_text, dont_filter=True,meta={"type":type,'page':new_page})
            for d in data_:
                dicts = {}
                url = d['article']['m_url']
                try:
                    dataSource = d['article']['category']['name']
                except:
                    dataSource = '界面新闻'
                try:
                    author = d['article']['author']['nick_name']
                except:
                    author = ''
                id = Utils.url_hash(url)
                title = d['article']['title']
                content_id = d['article']['id']
                pubdate_datetime = d['article']['publish_time']
                pubdate = Utils.process_timestamp(pubdate_datetime)
                pubdate = str(self.t.datetimes(pubdate))
                if not self.t.time_is_Recent(pubdate):
                    yield None
                else:
                    dicts['url'] = url
                    dicts['id'] = id
                    dicts['title'] = title
                    dicts['pubdate'] = pubdate
                    dicts['dataSource'] = dataSource
                    dicts['author'] = author
                    if self.redis.check_exist_2("wenzhangquchong", id, '') == 0:
                        print('该id:%s已存在' % id)
                        yield None
                    else:
                        # 获取详情页
                        get_content = f'https://papi.jiemian.com/app/article/index?id={content_id}'
                        yield scrapy.Request(url=get_content,headers=self.headers,callback=self.parse,dont_filter=True,meta=dicts)

    def parse(self, response):
        content_data = json.loads(response.text)
        item = NewsItem()
        quote_html = content_data['result']['article']['content']
        html = unquote(quote_html)
        item['id'] = response.meta['id']
        item['url'] = response.meta['url']
        item['title'] =response.meta['title']
        item['pubdate'] =response.meta['pubdate']
        item['content'] =remove_tags(html)
        item['author'] = response.meta['author']
        item['formats'] = "web"
        item['dataSource'] = response.meta['dataSource']
        item['serchEnType'] = "界面新闻"
        item['html'] = html
        item['updateTime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        item['collectProcess'] = 'crawl_news'
        item['serverIp'] = "113.128.12.74"
        # print(item)
        yield item